package com.sbp.message.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dap.param.StringInput;
import com.dap.utils.DateUtil;
import com.sbp.message.api.entity.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SmsServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private SmsServiceInvoker smsServiceInvoker;


    private static String formatErrorMessage(String errorMessage) {
        if (null != errorMessage && errorMessage.length() > 100) {
            return errorMessage.substring(0, 100);
        } else {
            return errorMessage;
        }
    }



    private boolean sendSms(JSONObject jsonParam, String mobile) {
        jsonParam.put("mobile", mobile);

        StringInput smsInput = new StringInput(jsonParam.toJSONString());
        smsInput.getCtrlData().setInternalRequestSource("messageCenterNotice");
        Integer sendResult = (Integer) smsServiceInvoker.invoke("unloginSmsSendSingleWithVerificationServiceImpl", smsInput);
        return null != sendResult && sendResult > 0;
    }
    private int sendSms(List<String> notifyMobileList, String errorMessage, Message message, String companyName,
            JSONObject jsonParam) {
        int successCount = 0;
        for (String mobile : notifyMobileList) {
            try {
                if (sendSms(jsonParam, mobile)) {
                    ++successCount;
                }
            } catch (Exception e) {
                logger.error("发送短信通知失败, mobile=" + mobile + ", errorMessage=" + errorMessage + ", message=" +
                             JSON.toJSONString(message) + ", companyName=" + companyName, e);
            }
        }
        return successCount;
    }


    private int sendNotifySms_ErpOrderInsert(List<String> notifyMobileList, String errorMessage, Message message, String companyName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", 1);
        jsonObject.put("smsTemplate", "SMS_196657614");
        jsonObject.put("smsPurposeType", 2);

        JSONObject contentJson = JSON.parseObject(message.getContent());

        JSONObject fields = new JSONObject();
        fields.put("dateStr", DateUtil.format(new Date(), "MM-dd HH:mm:ss"));
        fields.put("errorDescription", formatErrorMessage(errorMessage));
        fields.put("messageId", message.getId());
        fields.put("messageDestination", message.getDestination());
        fields.put("orderSn", contentJson.getString("orderId"));
        fields.put("customerCode", contentJson.getString("empNoBuy"));
        fields.put("companyName", companyName);
        jsonObject.put("fields", fields);

        return sendSms(notifyMobileList, errorMessage, message, companyName, jsonObject);
    }

    private int sendNotifySms_ErpReceiveBack_Common(List<String> notifyMobileList, String errorMessage, Message message, String companyName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", 1);
        jsonObject.put("smsTemplate", "SMS_215315528");
        jsonObject.put("smsPurposeType", 2);

        JSONObject contentJson = JSON.parseObject(message.getContent());
        JSONObject serviceAfterSalesJson = JSON.parseObject(contentJson.getString("serviceAfterSalesJsonStr"));

        JSONObject fields = new JSONObject();
        fields.put("sellerName", serviceAfterSalesJson.getString("sellerName"));
        fields.put("buyerName", serviceAfterSalesJson.getString("buyerName"));
        fields.put("occurTime", DateUtil.format(new Date(), "MM-dd HH:mm:ss"));
        fields.put("messageId", message.getId());
        fields.put("errorInfoStr", formatErrorMessage(errorMessage));

        fields.put("buyerK3No", contentJson.getString("custNumber"));
        fields.put("tocketNo", contentJson.getString("outerOrderId"));

        jsonObject.put("fields", fields);

        return sendSms(notifyMobileList, errorMessage, message, companyName, jsonObject);
    }

    private int sendNotifySms_Default(List<String> notifyMobileList, String errorMessage, Message message, String companyName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", 1);
        jsonObject.put("smsTemplate", "SMS_215340045");
        jsonObject.put("smsPurposeType", 2);

        JSONObject fields = new JSONObject();
        fields.put("dateStr", DateUtil.format(new Date(), "MM-dd HH:mm:ss"));
        fields.put("errorDescription", formatErrorMessage(errorMessage));
        fields.put("messageId", message.getId());
        fields.put("messageDestination", message.getDestination());
        fields.put("companyName", companyName);
        jsonObject.put("fields", fields);

        return sendSms(notifyMobileList, errorMessage, message, companyName, jsonObject);
    }


    public int sendNotifySms(String errorMessage, Message message, String companyName, List<String> notifyMobileList) {
        switch (message.getDestination()) {
            case "erp.order.insert":
                return sendNotifySms_ErpOrderInsert(notifyMobileList, errorMessage, message, companyName);

            case "erp.receiveBackBill.insert":
            case "erp.salesBackInform.insert":
            case "erp.salesBack.insert":
                return sendNotifySms_ErpReceiveBack_Common(notifyMobileList, errorMessage, message, companyName);

            default:
                return sendNotifySms_Default(notifyMobileList, errorMessage, message, companyName);
        }
    }

}
